//
//  BangoHomeView.m
//  Bango
//
//  Note this view is intended to test out the actual api methods directly. When automatically called methods are added to the app delegate then this view can contain
//  references to deleted profiles (and hence dealloced memory). To use this view when hooks are auto triggered by the app delegate (such as profile submission in sesssion startup),
//  Use the "refresh table" button before you do anything else.
// 

#import "BangoHomeView.h"
#import "BangoAppDelegate.h"
#import "BGOProfile.h"
#import "BGOAnalyticsManager.h"
#import "BGOAnalyticsConstants.h"
#import "BangoConfigConstants.h"
#import "BGOTransmissionModeConstants.h"
#import "BGODataType.h"
#import "BGOEvent.h"
#import "BGOEventParameter.h"
#import "BGOPersistenceManager.h"
#import "LoggingLevelView.h"
#import "BangoConfigConstants.h"
#import "WebAnalyticsView.h"
@implementation BangoHomeView

@synthesize tableView=_tableView;

// buttons
@synthesize createProfileButton, endSessionButton, eventValue;

@synthesize entityName;

@synthesize profiles=_profiles;
@synthesize profileIndex=_profileIndex;
@synthesize eventIndex=_eventIndex;

#pragma mark -
#pragma mark View lifecycle

/*
 - (void)viewDidLoad {
 [super viewDidLoad];
 
 // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
 // self.navigationItem.rightBarButtonItem = self.editButtonItem;
 }
 */

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
	if(self.entityName == nil) {
		self.entityName = @"Profile";
        
        _profileIndex = -1;
        _eventIndex = -1;
	}
    
    self.navigationItem.title = [self.entityName stringByAppendingString:@"(s)"];

	[_tableView reloadData];
	
}

-(void) loadProfiles{
	NSLog(@"> %s", __PRETTY_FUNCTION__);
    //	BangoAppDelegate *appDelegate = [BangoAppDelegate sharedAppDelegate];
    //	NSManagedObjectContext* context = appDelegate.managedObjectContext;
    
	
    //	if(entitySearchPredicate == nil)
    //	{
    // Use the CoreDataHelper class to get all objects of the given
    // type sorted by the "Name" key
    //		BangoAppDelegate *appDelegate = [BangoAppDelegate sharedAppDelegate];
    //		NSManagedObjectContext* context = appDelegate.managedObjectContext;
    
    // TODO: (WS) uncomment line below
    
    //		NSMutableArray* mutableFetchResults = [[BGOCoreDataHelper getObjectsFromContext:self.entityName :sortByField :YES ]retain];
    //		
    //		for(int i=0; i<[mutableFetchResults count]; i++) {
    //			NSLog(@"found %@", ((BGOProfile*) [mutableFetchResults objectAtIndex:i]).created);
    //		}
    //		
    //		self.items = mutableFetchResults;
    //	}
    //	else {		
    //		NSMutableArray* mutableFetchResults = [[BGOCoreDataHelper searchObjectsInContext:self.entityName :entitySearchPredicate :sortByField :YES]retain];
    //		self.items = mutableFetchResults;
    //	}
    
    self.profiles = [[BGOPersistenceManager sharedPersistenceManager] getProfilesForPost:NO];
	
	[_tableView reloadData];
}



// loads the view
- (void) viewWillAppear:(BOOL)animated {
    
    [BGOAnalyticsManager sharedManager].delegate = self;
    self.tabBarController.tabBar.hidden=NO;

	// Load profiles if we havn't already done so
	if (_profiles == nil) {
		[self loadProfiles];
	}
}

/*
 - (void)viewDidAppear:(BOOL)animated {
 [super viewDidAppear:animated];
 }
 */
/*
 - (void)viewWillDisappear:(BOOL)animated {
 [super viewWillDisappear:animated];
 }
 */
/*
 - (void)viewDidDisappear:(BOOL)animated {
 [super viewDidDisappear:animated];
 }
 */

 // Override to allow orientations other than the default portrait orientation.
 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
 // Return YES for supported orientations
 return (interfaceOrientation == UIInterfaceOrientationPortrait);
 }
 


#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}


// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView
 numberOfRowsInSection:(NSInteger)section {
    NSInteger number = 0;
    
    if ([@"Profile" isEqualToString:self.entityName]) {
        number = _profiles.count;
    } else if ([@"Event" isEqualToString:self.entityName]) {
        BGOProfile *profile = (BGOProfile *)[_profiles objectAtIndex:_profileIndex];
        
        if (profile.events != nil) {
            number = profile.events.count;
        }
    } else if ([@"EventParameter" isEqualToString:self.entityName]) {
        BGOProfile *profile = (BGOProfile *)[_profiles objectAtIndex:_profileIndex];
        BGOEvent *event = (BGOEvent *)[profile.events objectAtIndex:_eventIndex];
        
        if (event.eventParameters != nil) {
            number = event.eventParameters.count;
        }
    }
    
    return number;
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)myTableView 
         cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	
	// Default cell identifier
	NSString *CellIdentifier = @"Cell";
	int indicator = UITableViewCellAccessoryNone;
	
    BGOProfile *profile = nil;
    BGOEvent *event = nil;
    BGOEventParameter *eventParameter = nil;
    
	// Check to see if the object has child elements and create appropriate cell identifier
	if ([@"Profile" isEqualToString:self.entityName]) {
        profile = (BGOProfile *)[_profiles objectAtIndex:indexPath.row];
		if (profile.events != nil && profile.events.count > 0) {
			indicator = UITableViewCellAccessoryDisclosureIndicator;
			CellIdentifier = @"CellWithDisclosure";
		}
	} else if ([@"Event" isEqualToString:self.entityName]) {
        profile = (BGOProfile *)[_profiles objectAtIndex:_profileIndex];
        event = (BGOEvent *)[profile.events objectAtIndex:indexPath.row];
        
		if (event.eventParameters != nil && 
            event.eventParameters.count > 0) {
			indicator = UITableViewCellAccessoryDisclosureIndicator;
			CellIdentifier = @"CellWithDisclosure";
		}
	} else if ([@"EventParameter" isEqualToString:self.entityName]) {
        profile = (BGOProfile *)[_profiles objectAtIndex:_profileIndex];
        event = (BGOEvent *)[profile.events objectAtIndex:_eventIndex];
        eventParameter = (BGOEventParameter *)[event.eventParameters objectAtIndex:indexPath.row];
    }
	
	// Create a cell.
    UITableViewCell *cell = [myTableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }
	
	cell.accessoryType = indicator;
	if (self.entityName == @"Profile") {
        NSMutableString *profileTitle = [NSMutableString string];
        if (profile.applicationKey != nil && ![@"" isEqualToString:profile.applicationKey]) {
            [profileTitle appendString:profile.applicationKey];
        } else {
            [profileTitle appendFormat:@"Profile %d", profile.id];
        }
        
        [profileTitle appendFormat:@" (%d events)", profile.events.count];
		
        cell.textLabel.text = profileTitle; 
        
		NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
		[dateFormat setDateFormat:@"EEEE MMMM d, YYYY H:mm:ss"];
		NSString *dateString = [dateFormat stringFromDate:profile.created];  
		[dateFormat release];
		
		cell.detailTextLabel.text = dateString;
        
        if ([cell respondsToSelector:@selector(backgroundView)]) {
            if (profile.isProfilePosted) {
                cell.backgroundView.backgroundColor = [UIColor orangeColor];
            } else {
                cell.backgroundView.backgroundColor = [UIColor whiteColor];
            }
        }
	}  else if(self.entityName == @"Event") {
		cell.textLabel.text = event.eventName;
        cell.detailTextLabel.text = event.eventValue;
        
        if ([cell respondsToSelector:@selector(backgroundView)]) {
            if (event.eventPosted) {
                cell.backgroundView.backgroundColor = [UIColor orangeColor];
            } else {
                cell.backgroundView.backgroundColor = [UIColor whiteColor];
            }
        }
	} else if(self.entityName == @"EventParameter") {
		cell.textLabel.text = eventParameter.eventValue;
        cell.detailTextLabel.text = eventParameter.eventValue;
	}
	
	
    return cell;
}






/*
 // Override to support conditional editing of the table view.
 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the specified item to be editable.
 return YES;
 }
 */


/*
 // Override to support editing the table view.
 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
 
 if (editingStyle == UITableViewCellEditingStyleDelete) {
 // Delete the row from the data source
 [_tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
 }   
 else if (editingStyle == UITableViewCellEditingStyleInsert) {
 // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
 }   
 }
 */


/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
 }
 */


/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */


#pragma mark -
#pragma mark Table view delegate

// Override to support row selection in the table view.
- (void)tableView:(UITableView *)tableView 
didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	
	if (self.entityName == @"Profile" || self.entityName == @"Event") {
		// Get the object the user selected from the array
        //		BGODataType *selectedObject = (BGODataType *)[items objectAtIndex:indexPath.row];
        // Create a new table view of this very same class.
        BangoHomeView *homeViewController = nil;
        
        // Pass the managed object context
        //		NSPredicate *predicate = nil;
        
        if (self.entityName == @"Profile") {
            BGOProfile *profile = (BGOProfile *)[_profiles objectAtIndex:indexPath.row];
            if (profile.events != nil && profile.events.count > 0) {
                if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
                    homeViewController = [[BangoHomeView alloc]
                                          initWithNibName:@"BangoHomeView-iPad" 
                                          bundle:[NSBundle mainBundle]];                
                } 
                else 
                {                
                    homeViewController = [[BangoHomeView alloc]
                                          initWithNibName:@"BangoHomeView" 
                                          bundle:[NSBundle mainBundle]];
                    // Running on iPhone or iPod touch
                    
                }
                
                homeViewController.entityName = @"Event";
                homeViewController.profileIndex = indexPath.row;
                homeViewController.eventIndex = -1;
                
                // Create a query predicate to find all child objects of the selected object. 
                //			predicate = [NSPredicate predicateWithFormat:@"(profile == %@)", selectedObject];
                //			sortByField =@"created";
            }
        } else if(self.entityName == @"Event") {
            BGOProfile *profile = (BGOProfile *)[_profiles objectAtIndex:_profileIndex];
            BGOEvent *event = (BGOEvent *)[profile.events objectAtIndex:indexPath.row];
            
            if (event.eventParameters != nil && event.eventParameters.count > 0) {
                
                if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
                    homeViewController = [[BangoHomeView alloc]
                                          initWithNibName:@"BangoHomeView-iPad" 
                                          bundle:[NSBundle mainBundle]];                
                } 
                else 
                {                
                    homeViewController = [[BangoHomeView alloc]
                                          initWithNibName:@"BangoHomeView" 
                                          bundle:[NSBundle mainBundle]];
                    // Running on iPhone or iPod touch

                }
                                
                
                homeViewController.entityName = @"EventParameter";
                homeViewController.profileIndex = self.profileIndex;
                homeViewController.eventIndex = indexPath.row;
                
                // Create a query predicate to find all child objects of the selected object.
                //			predicate = [NSPredicate predicateWithFormat:@"(event == %@)", selectedObject];
                //			sortByField = @"eventTime";
            }
        }
        
        //		[homeViewController setEntitySearchPredicate:predicate];
        
        if (homeViewController != nil) {
            //Push the new table view on the stack
            [self.navigationController pushViewController:homeViewController animated:YES];
            [homeViewController release]; 
        }
	} else if(self.entityName == @"EventParameter") {
        //		sortByField = @"eventName";
	}
}


#pragma mark -
#pragma mark Button handlers

// emulates the starting of a session
- (IBAction) createProfile: (id) sender{
	NSLog(@"> %s", __PRETTY_FUNCTION__);
	
	NSDictionary *eventParameters = [[NSDictionary alloc] initWithObjectsAndKeys: @"tommy session start campaign test",
                                     @"BGO_CAMPAIGN", @"tommy custom value", @"BGO_CUSTOM1", nil];
    
	[[BGOAnalyticsManager sharedManager] onStartSessionWithApplicationId:[[NSUserDefaults standardUserDefaults] objectForKey:           BANGO_APPLICATION_ID]
        eventParameters:eventParameters
        eventDetail:@"test event detail - profile created by test app"
        eventValue:@"test event value - start session"];
	
	[eventParameters release];
    
	[self loadProfiles];
	
}

// emulates the ending of a session
- (IBAction) endSession: (id) sender{
	NSLog(@"> %s", __PRETTY_FUNCTION__);
	
	NSDictionary *eventParameters = [[NSDictionary alloc] initWithObjectsAndKeys: @"tommy session end campaign test", @"BGO_CAMPAIGN", @"tommy custom value", @"BGO_CUSTOM1", nil];
	
	// create NSDictionary with mandatory params
	// date is mandatory
    
	[[BGOAnalyticsManager sharedManager] onEndSessionWithEventParameters:eventParameters eventDetail:@"test app detail - emulating end session" eventValue:@"test app value - emulating end session"];
	
	[eventParameters release];
	
	[self loadProfiles];
	
}

// emulates the starting of a video
- (IBAction) startVideo: (id) sender{
	NSLog(@"> %s", __PRETTY_FUNCTION__);
	
	NSDictionary *eventParameters = [[NSDictionary alloc] initWithObjectsAndKeys: @"tommy video start emulation", @"BGO_CAMPAIGN", @"tommy custom value", @"BGO_CUSTOM1", nil];
	[[BGOAnalyticsManager sharedManager] onDemandVideoStartWithEventParameters:eventParameters eventDetail:@"test app detail - emulating start video" eventValue:@"test app value - emulating start video"];
	
	[eventParameters release];
	
	[self loadProfiles];
}

// emulates the stoping of a video
- (IBAction) endVideo: (id) sender{
	NSLog(@"> %s", __PRETTY_FUNCTION__);
	
	NSDictionary *eventParameters = [[NSDictionary alloc] initWithObjectsAndKeys: @"tommy video stop emulation", @"BGO_CAMPAIGN", @"tommy custom value", @"BGO_CUSTOM1", nil];
	
	[[BGOAnalyticsManager sharedManager] onDemandVideoStopWithEventParameters:eventParameters eventDetail:@"test app detail - emulating end video" eventValue:@"test app value - emulating end video"];
	
	[eventParameters release];
	
	[self loadProfiles];	
}

// handles start idle emulation
- (IBAction) startIdle: (id) sender{
	NSLog(@"> %s", __PRETTY_FUNCTION__);
	
	NSDictionary *eventParameters = [[NSDictionary alloc] initWithObjectsAndKeys: @"tommy idle start emulation", @"BGO_CAMPAIGN", @"tommy custom value", @"BGO_CUSTOM1", nil];
	[[BGOAnalyticsManager sharedManager] onIdleWithEventParameters:eventParameters eventDetail:@"test app detail -emulating start idle" eventValue:@"test app value - emulating start idle"];
	
	[eventParameters release];
	
	[self loadProfiles];
	
}

// handles end idle emulation
- (IBAction) endIdle: (id) sender{
	NSLog(@"> %s", __PRETTY_FUNCTION__);
	NSDictionary *eventParameters = [[NSDictionary alloc] initWithObjectsAndKeys: @"tommy idle start emulation", @"BGO_CAMPAIGN", @"tommy custom value", @"BGO_CUSTOM1", nil];
	[[BGOAnalyticsManager sharedManager] onResumeWithEventParameters:eventParameters eventDetail:@"test app detail -emulating on resume" eventValue:@"test app value - emulating on resume"];
	
	[eventParameters release];
	[self loadProfiles];	
}

// emulates user search
- (IBAction) onSearch: (id) sender{
	NSLog(@"> %s", __PRETTY_FUNCTION__);
	
	NSDictionary *eventParameters = [[NSDictionary alloc] initWithObjectsAndKeys: @"tommy search emulation", @"BGO_CAMPAIGN", @"tommy custom value", @"BGO_CUSTOM1", nil];
	[[BGOAnalyticsManager sharedManager] onSearchWithEventParameters:eventParameters eventDetail:@"test app detail - emulating search" eventValue:@"test app value - emulating search"];
	
	[eventParameters release];
	
	[self loadProfiles];
}

// emulates page View
- (IBAction) onPageView: (id) sender{
	NSLog(@"> %s", __PRETTY_FUNCTION__);
	
	NSString *page;
	
	// set to default value if no value in eventValue box
	if(self.eventValue.text == nil || [self.eventValue.text isEqualToString:@""]) {
		page = @"test app value - emulating page view";
	} else {
		page = self.eventValue.text;
	}
	
	NSDictionary *eventParameters = [[NSDictionary alloc] initWithObjectsAndKeys: @"tommy page view emulation", @"BGO_CAMPAIGN", @"tommy custom value", @"BGO_CUSTOM1", nil];
	[[BGOAnalyticsManager sharedManager] onPageViewWithEventParameters:eventParameters eventDetail:@"test app detail - emulating page view" eventValue:page];
	
	[eventParameters release];
	
	[self loadProfiles];
}

// handles logging of an error
- (IBAction) logError: (id) sender{
	NSLog(@"> %s", __PRETTY_FUNCTION__);
	NSDictionary *eventParameters = [[NSDictionary alloc] initWithObjectsAndKeys:@"tommy error emulation",
                                     @"BGO_CAMPAIGN",
                                     @"tommy custom value",
                                     @"BGO_CUSTOM1", 
                                     nil];
	
	NSNumber *errorLevel = [NSNumber numberWithInt:BGO_ERROR_USER];
	NSString *errorId = @"SuperBadError(TEST)";
    
	[[BGOAnalyticsManager sharedManager] onErrorWithEventParameters:eventParameters message:@"test app detail -emulating error" eventClass:@"test app value - emulating on error"
                                                    eventErrorLevel:errorLevel eventErrorId:errorId];
	
	[eventParameters release];
	[self loadProfiles];	
}

// transmits the data to bango
- (IBAction) transmit: (id) sender{
	NSLog(@"> %s", __PRETTY_FUNCTION__);
	
	// this uses the transmit all method
	
	[[BGOAnalyticsManager sharedManager] commenceTransmissionWithMode:BGO_TRANSMIT_ALL];
}

// refreshes the table
// todo could add delegate to the api for after successful post
- (IBAction) refresh: (id) sender{
	NSLog(@"> %s", __PRETTY_FUNCTION__);
	[self loadProfiles];
}

//call loggingLevel View
- (IBAction)setLoggingLevel: (id) sender
{
    LoggingLevelView *loggingLevelVC=[[LoggingLevelView alloc]init];
    [self presentModalViewController:loggingLevelVC animated:YES];
    [LoggingLevelView release];
}
//shows web Analytics
- (IBAction)showWebAnalytics: (id) sender
{
    WebAnalyticsView *webAnalytics=[[WebAnalyticsView alloc]init];
    [self.navigationController pushViewController:webAnalytics animated:YES];
    [webAnalytics release];
}

#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
}


- (void)dealloc {
	[_profiles release];
    [super dealloc];
}


#pragma mark Delegate optional methods
- (void)transmitFailure {
    UIAlertView * warningView = [[[UIAlertView alloc] initWithTitle:@"Warning"  
                                                            message:@"There has been an issue transmitting the stored analytics data" 
                                                           delegate:nil 
                                                  cancelButtonTitle:@"OK"  
                                                  otherButtonTitles:nil] autorelease]; 
    
    [warningView show];
}

- (void) transmitSuccess {
    [self loadProfiles];
}

@end

